<?php

class YandexParserController extends Controller {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations			  
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'get' actions
                'actions' => array('get', 'index', 'getByUrl', 'getNewModels'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    private $cookie = '';
    public $products = array();
    public $catsReplace = array(
        'Мобильные телефоны' => '1',
        'Планшеты' => '2',
        'Телевизоры и плазменные панели' => '9',
        'Цифровые фотокамеры' => '6',
        'Ноутбуки' => '3',
        'Электронные книги' => '7',
        'Цифровые плееры' => '8',
        'Наручные часы' => '10',
    );

    function setCookie($cookie) {
        $this->cookie = $cookie;
    }

    public function actionIndex() {
        Yii::log('Message Here...', CLogger::LEVEL_WARNING);
        $this->render('index');
    }

    public function getAllProductsFromDB($conditions = array()) {
        $criteria = new CDbCriteria();
        $criteria->select = '"pageId", "pageTitle"';
        if (!empty($conditions))
            foreach ($conditions as $key => $value)
                $criteria->compare($key, $value, TRUE);
        $criteria->compare('"pageType"', 'model');
        $models = CHtml::listData(Page::model()->findAll($criteria), 'pageId', 'pageTitle');
        return $models;
    }

    public function getSimilarModel($title = '', $brand = '', $yaId = null) {
        if (!empty($yaId)) {
            $model = Page::model()->find('"pageYandexId" LIKE \'%' . (int) $yaId . '%\'');
            if ($model !== null)
                return $model;
        }
        $brand = getUrl::cleanString($brand);
        $array = explode(" ", strtolower($title));
        $session = Yii::app()->session['brandsCache'];
        if (isset($session[$brand])) {
            $products = $session[$brand];
        } else {
            $products = $this->getAllProductsFromDB(array('"pageUrl"' => $brand));
            Yii::app()->session['brandsCache'] = array($brand => $products);
        }
        if (empty($products))
            return null;
        foreach ($products as $pk => $value) {
            if ($title == $value)
                return Page::model()->findByPk($pk);
            $ex = explode(" ", strtolower($value));
            $m = array_intersect($ex, $array);
            $score[$pk] = count($m);
        }
        $maxScore = max($score);
        return Page::model()->findByPk(array_search($maxScore, $score));
    }

    public function getCategoryByTitle($title = '') {
        return Page::model()->findByPk($title);
    }

    public function getBrandByTitleAndCategoryID($title = '', $categoryID = 0) {
        $sql = "SELECT \"pageUrl\", \"pageId\" FROM {{pages}} WHERE \"pageTitle\" ILIKE '$title' AND \"pageParent\" = '$categoryID' AND \"pageType\" = 'brand' LIMIT 1";
        return Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryAll();
        ;
    }

    public function Actions_($post) {
        if (isset($post)) {
            foreach ($post['action'] as $key => $value) {
                switch ($post['action'][$key]) {
                    case "add":
                        $categoryTitle = $post['category'][$key];
                        $brandTitle = $post['brand'][$key];
                        $modelTitle = $post['model'][$key];
                        if (empty($modelTitle) && empty($categoryTitle) && empty($brandTitle)) {
                            Yii::app()->user->setFlash('error', 'Модель ' . $brandTitle . ' не добавлен');
                            $this->refresh();
                            break;
                        }

                        $mainImageUrl = $post['mainImageUrl'][$key];
                        $category = $this->getCategoryByTitle($categoryTitle);

                        $brand2 = $this->getBrandByTitleAndCategoryID($brandTitle, $category->pageId);
                        if (empty($brand2)) {
                            $pageUrlBrand = $category->pageUrl . '/' . getUrl::cleanString($brandTitle);
                            $sql = "INSERT INTO {{pages}} (\"pageType\", \"pageAction\", \"pageParent\", \"pageUrl\", \"pageImages\", \"pageTitle\") VALUES ('brand', 'list/brand', '$category->pageId', '$pageUrlBrand', '', '$brandTitle')";
                            Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->query();
                        }

                        sleep(1);
                        $brand = $this->getBrandByTitleAndCategoryID($brandTitle, $category->pageId);

                        $brand = isset($brand[0]) ? $brand[0] : $brand;

                        $pageUrl = $brand['pageUrl'] . '/' . getUrl::cleanString($modelTitle);
                        $newFileName = getUrl::cleanString($brandTitle) . '-' . getUrl::cleanString($modelTitle) . '.' . pathinfo($mainImageUrl, PATHINFO_EXTENSION);

                        if (!empty($modelTitle) && !empty($categoryTitle) && !empty($brandTitle)) {
                            if (!empty($mainImageUrl))
                                copy($mainImageUrl, 'uploads/images/model/' . $newFileName);
                            $sql = "INSERT INTO {{pages}} (\"pageType\", \"pageAction\", \"pageParent\", \"pageUrl\", \"pageImages\", \"pageTitle\", \"pageYandexId\") VALUES ('model', 'list/model', '{$brand['pageId']}', '$pageUrl', '$newFileName', '$modelTitle', '{$post['yaId'][$key]}')";
                            Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->execute();
                        } else {
                            Yii::app()->user->setFlash('error', 'Модель ' . $post['brand'][$key] . ' не добавлен');
                        }
                        break;
                    case "update":
                        $model = Page::model()->findByPk($post['modelID'][$key]);
                        $modelTitle = $post['model'][$key];
                        $mainImageUrl = $post['mainImageUrl'][$key];
                        $newFileName = getUrl::cleanString($modelTitle) . '.' . pathinfo($mainImageUrl, PATHINFO_EXTENSION);
                        copy($mainImageUrl, 'uploads/images/brand/' . $newFileName);
                        if (file_exists('uploads/images/brand/' . $model->pageImages) && !empty($model->pageImages))
                            unlink('uploads/images/brand/' . $model->pageImages);
                        $model->pageImages = $newFileName;
                        $model->pageTitle = $post['model'][$key];
                        $model->save(false);
                        break;
                    case "skip":
                        break;
                }
            }
        }
    }

    public function getCategoryDropdown() {
        return CHtml::dropDownList('category', $this->catsReplace, CHtml::listData(Page::model()->findAll("\"pageType\" = 'category'"), 'pageId', 'pageTitle'));
    }

    protected function getContent($url) {
        $this->setcookie("yandex_gid=213;yandexmarket=10,RUR,1,,,,2,0,0");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_COOKIE, $this->cookie);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        $result = curl_exec($ch);
        $header = curl_getinfo($ch);
        curl_close($ch);
        return [$result, $header];
    }

    public function actionGet() {
        set_time_limit(0);
        $this->pageTitle = 'Yandex Parser';
        if (isset($_GET['yandex']))
            $this->products = array_unique(explode(',', str_replace(" ", "", $_GET['yandex'])));
        Yii::import('ext.phpQuery');
        $product = array();
        foreach ($this->products as $key => $value) {

            $url = 'http://market.yandex.ru/model.xml?modelid=' . $value;
            $result = $this->getContent($url);

            if (isset($result[1]['redirect_url']) && !empty($result[1]['redirect_url'])) {
                $result = $this->getContent($result[1]['redirect_url']);
            }
            $result = $result[0];

            $doc = phpQuery::newDocument($result);
            $url = parse_url(pq($doc['.b-switcher__link.b-model-tabs__tab-spec'])->attr('href'));
            $result = $this->getContent('http://market.yandex.ru/model.xml?' . $url['query']);
            $result = $result[0];

            $doc = phpQuery::newDocument($result);
            $product['h1Title'][] = trim(strip_tags(str_replace('новинка', '', pq($doc['h1.b-page-title__title'])->html())));
            $product['category'][] = trim(strip_tags(pq($doc['.b-max-width .b-breadcrumbs span a:first'])->html()));
            $product['brand'][] = trim(strip_tags(str_replace($product['category'][$key], '', pq($doc['a.b-breadcrumbs__link'])->html())));
            $product['model'][] = trim(str_replace($product['brand'][$key], '', $product['h1Title'][$key]));
            $product['yaId'][] = $value;
            $image = pq($doc['.b-model-pictures__big a'])->attr('href');
            if (empty($image)) {
                $image = pq($doc['.b-model-pictures img'])->attr('src');
            }
            $product['mainImageUrl'][] = $image;
            sleep(1);
        }
        if (isset($_POST['action'])) {
            $this->Actions_($_POST);
        }
//        echo '<pre>';
//        print_r($product);
//        exit;
        $this->render('get', array('product' => $product));
    }

    public function actionGetByUrl($url) {
        set_time_limit(0);
        $str = '';
        Yii::import('ext.phpQuery');
        $limit = isset($_GET['limit']) ? $_GET['limit'] : 10;
        $output = mTools::getYaContent($url, array('ip' => '139.210.98.86', 'port' => '8080'), $limit);

//                echo '<pre>';
//                print_r($output);exit;

        $document = phpQuery::newDocument($output[0]);
        $pager = pq($document['.b-pager__pages'])->html();
        if (!empty($pager)) {
            $nextPage = '';
            $flag = false;
            $nextPage = pq($document['.b-pager span .b-pager__next'])->attr('href');
            while (!$flag) {
                sleep(1);
                $out = mTools::getYaContent('http://market.yandex.ru/' . $nextPage, array('ip' => '139.210.98.86', 'port' => '8080'), $limit);
                $d = phpQuery::newDocument($out[0]);
                $nextPage = pq($d['.b-pager span .b-pager__next'])->attr('href');
                if (empty($nextPage))
                    $flag = true;
                $str .= $out[0];
            }
        }
        $doc = phpQuery::newDocument($output[0] . $str);
        $ids = array();
        $category = trim(strip_tags(pq($doc['.b-breadcrumbs a:nth-child(3):first'])->text()));
        $brand = trim(strip_tags(pq($doc['.b-breadcrumbs b:first'])->text()));
        foreach ($doc['.page__b-offers__guru .b-offers'] as $id) {
            preg_match('@(.*)modelid=(\d+)(.*)@', pq($id)->find('.b-offers__pict a')->attr('href'), $content);
            if (isset($content[2])) {
                $h1 = trim(pq($id)->find('.b-offers__desc .b-offers__title a')->text());
                $product['mainImageUrl'][] = str_replace('&size=2', '', pq($id)->find('.b-offers__pict a img')->attr('src'));
                $product['h1Title'][] = $h1;
                $product['category'][] = $category;
                $product['brand'][] = $brand;
                $product['model'][] = mb_substr(str_replace($brand, '', $h1), 1, strlen($h1), 'utf-8');
                $product['yaId'][] = $content[2];
            }
        }
        if (isset($_POST['action'])) {
            $this->Actions_($_POST);
        }

        $this->render('get', array('product' => $product));
    }

    public function actionGetNewModels() {
        set_time_limit(0);
        Yii::import('ext.phpQuery');
        $out = Yii::app()->curl->get('http://market.yandex.ru/guru.xml?CMD=-RR=9,0,0,0-VIS=270-CAT_ID=160043-EXC=1-PG=10&hid=91491');

        $doc = phpQuery::newDocument($out);
        $ids = array();
        $category = trim(strip_tags(pq($doc['.b-breadcrumbs a:nth-child(3):first'])->text()));
        $brand = trim(strip_tags(pq($doc['.b-breadcrumbs b:first'])->text()));
        $criteria = new CDbCriteria();
        $criteria->select = '"pageId", "pageTitle"';
        $criteria->compare('"pageType"', 'model');
        foreach ($doc['.page__b-offers__guru .b-offers'] as $id) {
            preg_match('@(.*)modelid=(\d+)(.*)@', pq($id)->find('.b-offers__pict a')->attr('href'), $content);
            if (isset($content[2])) {
                $criteria->compare('"pageYandexId"', (int) $content[2], true);
                $model = Page::model()->find($criteria);
                if ($model !== null) {
                    $products[] = array(
                        'status' => 'yes',
                        'product' => (array) $model
                    );
                } else {
                    $product = array(
                        'yaId' => $content[2],
                        'title' => trim(strip_tags(str_replace('новинка', '', pq($doc['h1.b-page-title__title'])->html()))),
                        'category' => trim(strip_tags(pq($doc['.b-max-width .b-breadcrumbs span a:first'])->html())),
                        'brand' => trim(strip_tags(pq($doc['.b-max-width .b-breadcrumbs span a:nth-child(2)'])->html())),
                        'model' => trim(strip_tags(str_replace('новинка', '', pq($doc['h1.b-page-title__title'])->html())))
                    );
                    $products[] = array(
                        'status' => 'no',
                        'product' => $product
                    );
                }
            }
        }
        echo '<pre>';
        print_r($products);exit;
    }

}
